package org.example.service;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.example.entity.Admin;

import java.io.*;
import java.util.Date;
import java.util.Properties;

/**
 * @author TonySong
 * @date 2025/7/28 0028
 * @time 16:52
 */
public class AdminService implements IAdminService{
    @Override
    public Admin login(String username, String password) {
        //todo：输入的账号和密码与Properties的账号和密码进行比较
        Properties props = new Properties();
        try (InputStream input = new FileInputStream("admin.properties")) {
            props.load(input);
            String name = props.getProperty("username");
            String pwd = props.getProperty("password");
            if (username.equals(name) && password.equals(pwd)) {

                Admin admin = new Admin();
                admin.setUsername(username);
                admin.setPassword(password);
                //读取xml
                getXml( admin);
                //将登录信息保存在admin.xml中
                saveXml( admin);
                return admin;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
        //todo：记录最后登录时间和登录次数
        return null;
    }
    public void saveXml(Admin admin) throws IOException {
        // 创建Document对象
        Document document = DocumentHelper.createDocument();
        // 创建根节点
        Element rootElement = DocumentHelper.createElement("Users");
        document.setRootElement(rootElement);
        // 创建子节点
        Element element = rootElement.addElement("user");
        Element username = element.addElement("username");
        username.setText(admin.getUsername());
        Element password = element.addElement("password");
        password.setText(admin.getPassword());
        Element lasttime = element.addElement("lasttime");
        lasttime.setText(admin.getLastTime().toString());
        Element count = element.addElement("count");
        count.setText(admin.getCount().toString());
        //保存到xml
        OutputFormat format = new OutputFormat("\t", true,"utf-8");
        OutputStream out = new FileOutputStream("user.xml");
        System.out.println("保存用户信息成功");

        XMLWriter writer = new XMLWriter(out, format);
        writer.write(document);
        writer.close();
    }
    public void getXml(Admin admin) throws IOException, DocumentException {
        File xmlFile = new File("user.xml");
        if (xmlFile.exists()) {
            SAXReader reader = new SAXReader();
            Document document = reader.read(xmlFile);
            Element root = document.getRootElement();
            Element userElement = root.element("user");

            // 获取上次登录时间和登录次数
            String lastTimeString = userElement.elementText("lasttime");
            String countString = userElement.elementText("count");

            // 设置最后登录时间
            admin.setLastTime(new Date());

            // 设置登录次数（原基础上+1）
            if (countString != null && !countString.isEmpty()) {
                int count = Integer.parseInt(countString);
                admin.setCount(count + 1);
            } else {
                admin.setCount(1);
            }
        } else {
            // 如果XML文件不存在，设置初始值
            admin.setLastTime(new Date());
            admin.setCount(1);
        }
    }
}
